package com.haibara.codesubmiteval.chain.userChain;

import cn.hutool.json.JSONUtil;
import com.haibara.codesubmiteval.constant.CommonConstant;
import com.haibara.codesubmiteval.constant.RedisKeyConstant;
import com.haibara.codesubmiteval.model.dto.user.UserAddRequest;
import com.haibara.codesubmiteval.model.entity.User;
import jakarta.annotation.Resource;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * 用户通过题目id集合默认值处理节点
 *
 * @Author: mengyu
 * @Date: 2025/4/28
 */
@Component
@Order(5)
public class AcceptedQuestionIdsDefaultValueHandler extends CreateUserDefaultValueHandler {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void handleDefaultValue(User user, UserAddRequest userAddRequest) {
        // Redis新增完成题目集合
        // 添加标记位 0
        stringRedisTemplate.opsForSet().add(
                RedisKeyConstant.getCompleteKey(
                        RedisKeyConstant.userAcceptedQuestionIdsSet, user.getId().toString()
                ), "0"
        );
        Set<Long> acceptedQuestionIds = userAddRequest.getAcceptedQuestionIds();
        if (acceptedQuestionIds == null || acceptedQuestionIds.isEmpty()) {
            user.setAcceptedQuestionIds(JSONUtil.toJsonStr(CommonConstant.getNewSetWith0()));
        } else {
            user.setAcceptedQuestionIds(JSONUtil.toJsonStr(acceptedQuestionIds));
            for (Long acceptedQuestionId : acceptedQuestionIds) {
                stringRedisTemplate.opsForSet().add(
                        RedisKeyConstant.getCompleteKey(
                                RedisKeyConstant.userAcceptedQuestionIdsSet, user.getId().toString()
                        ), acceptedQuestionId.toString()
                );
            }
        }
        if (next != null) next.handleDefaultValue(user, userAddRequest);
    }
}
